package com.eliza.base.views.learn.widget

import android.content.Context
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.glance.Button
import androidx.glance.ButtonDefaults
import androidx.glance.GlanceId
import androidx.glance.GlanceModifier
import androidx.glance.GlanceTheme
import androidx.glance.action.ActionParameters
import androidx.glance.action.actionParametersOf
import androidx.glance.action.clickable
import androidx.glance.appwidget.CheckBox
import androidx.glance.appwidget.CheckboxDefaults
import androidx.glance.appwidget.RadioButton
import androidx.glance.appwidget.RadioButtonDefaults
import androidx.glance.appwidget.Switch
import androidx.glance.appwidget.SwitchDefaults
import androidx.glance.appwidget.action.actionRunCallback
import androidx.glance.appwidget.appWidgetBackground
import androidx.glance.appwidget.cornerRadius
import androidx.glance.appwidget.lazy.LazyColumn
import androidx.glance.appwidget.selectableGroup
import androidx.glance.background
import androidx.glance.color.ColorProvider
import androidx.glance.currentState
import androidx.glance.layout.Alignment
import androidx.glance.layout.Box
import androidx.glance.layout.Column
import androidx.glance.layout.ContentScale
import androidx.glance.layout.Row
import androidx.glance.layout.fillMaxSize
import androidx.glance.layout.fillMaxWidth
import androidx.glance.layout.height
import androidx.glance.layout.padding
import androidx.glance.layout.size
import androidx.glance.material3.ColorProviders
import androidx.glance.text.FontStyle
import androidx.glance.text.FontWeight
import androidx.glance.text.Text
import androidx.glance.text.TextAlign
import androidx.glance.text.TextDecoration
import androidx.glance.text.TextStyle
import androidx.glance.unit.ColorProvider
import com.eliza.base.R
import com.eliza.base.ui.theme.DemoColorScheme

// 创建界面

//
val CountClicksKey = intPreferencesKey("CountClicks")

// Defines an action key for [actionRunCallback]
val ClickValueKey = ActionParameters.Key<Int>("ClickValue")

object WidgetX {
    @Composable
    fun Show(context: Context, id: GlanceId) {
        Column {
            var count by remember {
                mutableIntStateOf(0)
            }
            Text(text = "FontsX $count", modifier = GlanceModifier.clickable {
                count = (count + 1) % 2
            })
            when (count) {
                0 -> ButtonX()
                1 -> ActionAppX()
                2 -> ButtonX()
                3 -> TintX()
                4 -> CompoundBtnX()
                5 -> ColorX()
                6 -> DefaultStateX()
            }
        }
    }

    @Composable
    private fun ActionAppX() {
        val selectableActionItem: @Composable (label: String, active: Boolean, onClick: () -> Unit) -> Unit =
            { label, active, onClick ->
                val style = if (active) {
                    TextStyle(
                        fontSize = 16.sp,
                        fontWeight = FontWeight.Bold,
                        textDecoration = TextDecoration.Underline,
                    )
                } else {
                    TextStyle(
                        fontSize = 16.sp,
                        fontWeight = FontWeight.Normal,
                        textDecoration = TextDecoration.None,
                        color = ColorProvider(
                            Color.Black.copy(alpha = 0.3f),
                            Color.White.copy(alpha = 0.3f)
                        )
                    )
                }
                Text(
                    text = label,
                    style = style,
                    modifier = GlanceModifier.padding(8.dp).clickable(onClick)
                )
            }

        Column(
            modifier = GlanceModifier.padding(R.dimen.external_padding).fillMaxSize()
                .appWidgetBackground().cornerRadius(R.dimen.corner_radius),
            verticalAlignment = Alignment.Vertical.CenterVertically,
            horizontalAlignment = Alignment.Horizontal.CenterHorizontally
        )
        {
            val pages = listOf("Activities", "Services", "Broadcasts")
            var currentPage by remember { mutableStateOf(pages.first()) }
            Row(
                GlanceModifier.fillMaxWidth(), Alignment.CenterHorizontally
            ) {
                for (page in pages) {
                    selectableActionItem(page, page == currentPage) { currentPage = page }
                }
            }

            when (currentPage) {
            }
        }
    }


    @Composable
    private fun ButtonX() {
        val primary = GlanceTheme.colors.primary
        val onPrimary = GlanceTheme.colors.onPrimary
        val colors = ButtonDefaults.buttonColors(
            backgroundColor = primary,
            contentColor = onPrimary
        )
        LazyColumn(
            modifier = GlanceModifier.fillMaxSize()
                .background(Color.DarkGray)
                .padding(16.dp)
        ) {
            item {
                Button(
                    text = "Standard Button",
                    onClick = {},
                    modifier = GlanceModifier,
                    colors = colors,
                    maxLines = 1
                )
            }
        }
    }

    @Composable
    private fun TintX() {
        Column {
            Box(
                // Tint a <shape>
                modifier = GlanceModifier
                    .size(width = 100.dp, height = 50.dp)
                    .background(
                        imageProvider = androidx.glance.ImageProvider(R.drawable.ic_launcher),
                        contentScale = ContentScale.FillBounds
                    )
            ) {}
            Box(
                // tint an AVD
                modifier = GlanceModifier
                    .size(width = 100.dp, height = 50.dp)
                    .background(
                        imageProvider = androidx.glance.ImageProvider(R.drawable.ic_launcher),
                        contentScale = ContentScale.FillBounds
                    )

            ) {}
        }
    }

    @Composable
    private fun CompoundBtnX() {
        val textStyle = TextStyle(
            color = ColorProvider(day = Color.Red, night = Color.Cyan),
            fontSize = 16.sp,
            fontWeight = FontWeight.Bold,
            fontStyle = FontStyle.Italic
        )
        val fillModifier = GlanceModifier.fillMaxWidth()
        Column(
            modifier = GlanceModifier.fillMaxSize().background(Color.LightGray)
                .padding(R.dimen.external_padding).cornerRadius(R.dimen.corner_radius)
                .appWidgetBackground(),
            verticalAlignment = Alignment.Vertical.CenterVertically,
            horizontalAlignment = Alignment.Horizontal.CenterHorizontally
        ) {


            var checkbox1Checked by remember { mutableStateOf(false) }
            var checkbox2Checked by remember { mutableStateOf(false) }
            var checkbox3Checked by remember { mutableStateOf(false) }
            var switch1Checked by remember { mutableStateOf(false) }
            var switch2Checked by remember { mutableStateOf(false) }
            var radioChecked by remember { mutableIntStateOf(0) }

            CheckBox(
                checked = checkbox1Checked,
                onCheckedChange = { checkbox1Checked = !checkbox1Checked },
                text = "Checkbox 1",
                modifier = GlanceModifier.height(56.dp).padding(bottom = 24.dp),
            )
            CheckBox(
                checked = checkbox2Checked,
                onCheckedChange = { checkbox2Checked = !checkbox2Checked },
                text = "Checkbox 2",
                style = textStyle,
                modifier = fillModifier,
                colors = CheckboxDefaults.colors(
                    checkedColor = ColorProvider(day = Color.Red, night = Color.Cyan),
                    uncheckedColor = ColorProvider(day = Color.Green, night = Color.Magenta)
                )
            )
            CheckBox(
                checked = checkbox3Checked,
                onCheckedChange = { checkbox3Checked = !checkbox2Checked },
                text = "Checkbox 3",
            )
            Switch(
                checked = switch1Checked,
                onCheckedChange = { switch1Checked = !switch1Checked },
                text = "Switch 1",
                colors = SwitchDefaults.colors(
                    checkedThumbColor = ColorProvider(day = Color.Red, night = Color.Cyan),
                    uncheckedThumbColor = ColorProvider(day = Color.Green, night = Color.Magenta),
                    checkedTrackColor = ColorProvider(day = Color.Blue, night = Color.Yellow),
                    uncheckedTrackColor = ColorProvider(day = Color.Magenta, night = Color.Green)
                ),
            )
            Switch(
                checked = switch2Checked,
                onCheckedChange = { switch2Checked = !switch2Checked },
                text = "Switch 2",
                style = textStyle,
                modifier = fillModifier
            )
            Column(modifier = fillModifier.selectableGroup()) {
                RadioButton(
                    checked = radioChecked == 0,
                    onClick = { radioChecked = 0 },
                    text = "Radio 1",
                    colors = RadioButtonDefaults.colors(
                        checkedColor = ColorProvider(day = Color.Red, night = Color.Cyan),
                        uncheckedColor = ColorProvider(day = Color.Green, night = Color.Magenta)
                    ),
                )
                RadioButton(
                    checked = radioChecked == 1,
                    onClick = { radioChecked = 1 },
                    text = "Radio 2",
                    colors = RadioButtonDefaults.colors(
                        checkedColor = ColorProvider(day = Color.Cyan, night = Color.Yellow),
                        uncheckedColor = ColorProvider(day = Color.Red, night = Color.Blue)
                    ),
                )
                RadioButton(
                    checked = radioChecked == 2,
                    onClick = { radioChecked = 2 },
                    text = "Radio 3",
                )
            }
            Row(modifier = fillModifier.selectableGroup()) {
                RadioButton(
                    checked = radioChecked == 0,
                    onClick = null,
                    text = "Radio 1",
                )
                RadioButton(
                    checked = radioChecked == 1,
                    onClick = null,
                    text = "Radio 2",
                )
                RadioButton(
                    checked = radioChecked == 2,
                    onClick = null,
                    text = "Radio 3",
                )
            }
        }
    }

    enum class Scheme { SystemM3, CustomM3, CustomM2 }

    @Composable
    private fun ColorX() {
        var currentScheme by remember { mutableStateOf(Scheme.SystemM3) }
        var doNothingAction = null
        val colors = when (currentScheme) {
            Scheme.SystemM3 -> GlanceTheme.colors
            Scheme.CustomM3 -> ColorProviders(
                light = DemoColorScheme.LightColors,
                dark = DemoColorScheme.DarkColors
            )

            Scheme.CustomM2 -> ColorProviders(
                light = DemoColorScheme.DarkColors,
                dark = DemoColorScheme.LightColors
            )
        }
        //================
        Column(
            GlanceModifier
                .fillMaxSize()
                .padding(16.dp)
                .background(GlanceTheme.colors.background)
        ) {
            Button(
                text = "Theme: $currentScheme",
                onClick = {
                    currentScheme = when (currentScheme) {
                        Scheme.SystemM3 -> Scheme.CustomM3
                        Scheme.CustomM3 -> Scheme.CustomM2
                        Scheme.CustomM2 -> Scheme.SystemM3
                    }
                },
                modifier = GlanceModifier.padding(8.dp)
            )
            Row(GlanceModifier.fillMaxWidth().padding(top = 8.dp)) {
                CheckBox(
                    modifier = GlanceModifier.defaultWeight(),
                    checked = false,
                    onCheckedChange = doNothingAction,
                    text = "Unchecked"
                )
                CheckBox(
                    modifier = GlanceModifier.defaultWeight(),
                    checked = true,
                    onCheckedChange = doNothingAction,
                    text = "Checked"
                )
            }

            Row(modifier = GlanceModifier.fillMaxWidth().padding(bottom = 8.dp)) {
                RadioButton(
                    modifier = GlanceModifier.defaultWeight(),
                    checked = false, onClick = doNothingAction, text = "Unchecked"
                )
                RadioButton(
                    modifier = GlanceModifier.defaultWeight(),
                    checked = true, onClick = doNothingAction, text = "Checked"
                )
            }

            Row(modifier = GlanceModifier.padding(bottom = 8.dp)) {
                Switch(checked = false, onCheckedChange = doNothingAction, text = "Off")
                Switch(checked = true, onCheckedChange = doNothingAction, text = "On")
            }

            @Composable
            fun ColorDebug() {
                @Composable
                fun Text(text: String, fg: ColorProvider, bg: ColorProvider) = Text(
                    text = text,
                    style = TextStyle(color = fg),
                    modifier = GlanceModifier.fillMaxWidth().background(bg).padding(6.dp)
                )
                Column(modifier = GlanceModifier.cornerRadius(8.dp)) {
                    with(GlanceTheme.colors) {
                        // Using  nested column because Glance uses statically generated layouts. Our
                        // Rows/Columns can only support a fixed number of children, so nesting is a workaround.
                        // The usual perf caveats for nested views still apply.
                        Column(modifier = GlanceModifier.background(Color.Transparent)) {
                            Text(text = "Primary / OnPrimary", fg = onPrimary, bg = primary)
                            Text(
                                text = "PrimaryContainer / OnPrimaryContainer",
                                fg = onPrimaryContainer,
                                bg = primaryContainer
                            )
                            Text(text = "Secondary / OnSecondary", fg = onSecondary, bg = secondary)
                            Text(
                                text = "SecondaryContainer / OnSecondaryContainer",
                                fg = onSecondaryContainer,
                                bg = secondaryContainer
                            )
                            Text(text = "Tertiary / OnTertiary", fg = onTertiary, bg = tertiary)
                        }
                        Column {
                            Text(
                                text = "TertiaryContainer / OnTertiaryContainer",
                                fg = onTertiaryContainer,
                                bg = tertiaryContainer
                            )
                            Text(text = "Surface / OnSurface", fg = onSurface, bg = surface)
                            Text(
                                text = "SurfaceVariant / OnSurfaceVariant",
                                fg = onSurfaceVariant,
                                bg = surfaceVariant
                            )
                            Text(
                                text = "InverseOnSurface / InverseSurface",
                                fg = inverseOnSurface,
                                bg = inverseSurface
                            )
                            Text(
                                text = "Background / OnBackground",
                                fg = onBackground,
                                bg = background
                            )
                            Text(text = "Error / OnError", fg = onError, bg = error)
                        }
                    }
                }
            }
            ColorDebug()

        }
    }

    @Composable
    private fun DefaultStateX() {
        // Get the current stored value for the given Key.
        val count = currentState(CountClicksKey) ?: 0

        Row(
            modifier = GlanceModifier.fillMaxSize()
                .appWidgetBackground()
                .padding(16.dp)
                .background(R.color.default_widget_background),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Button(
                modifier = GlanceModifier.defaultWeight(),
                text = "-",
                style = TextStyle(textAlign = TextAlign.Center),
                onClick = actionRunCallback<ClickAction>(
                    actionParametersOf(ClickValueKey to -1)
                )
            )
            Text(
                modifier = GlanceModifier.defaultWeight(),
                text = "$count",
                style = TextStyle(textAlign = TextAlign.Center)
            )
            Button(
                modifier = GlanceModifier.defaultWeight(),
                text = "+",
                style = TextStyle(textAlign = TextAlign.Center),
                onClick = actionRunCallback<ClickAction>(
                    actionParametersOf(ClickValueKey to 1)
                )
            )
        }
    }

}

